package com.haohan.cloud.scm.common.tools.handler;

import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.JsonDeserializer;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.module.SimpleModule;
import org.springframework.context.annotation.Bean;
import org.springframework.http.converter.json.Jackson2ObjectMapperBuilder;
import org.springframework.stereotype.Component;

import java.io.IOException;

/**
 * @author dy
 * @date 2019/10/16
 */
@Component
public class ScmStringJsonConvert {

    @Bean
    public ObjectMapper stringTrimObjectMapper(Jackson2ObjectMapperBuilder builder) {
        //解析器
        ObjectMapper objectMapper = builder.createXmlMapper(false).build();
        //注册解析器
        SimpleModule xssModule = new SimpleModule("ScmStringJsonSerializer");
        xssModule.addDeserializer(String.class, new JsonDeserializer<String>() {
            @Override
            public Class<String> handledType() {
                return String.class;
            }

            @Override
            public String deserialize(JsonParser p, DeserializationContext c) throws IOException, JsonProcessingException {
                String value = p.getValueAsString();
                if (null != value) {
                    // 截取首尾空白符
                    value = value.trim();
                }
                return value;
            }
        });
        objectMapper.registerModule(xssModule);
        //返回
        return objectMapper;
    }

}
